const fs = require("fs");
const path = require("path");
const sql = "select * from line;";

const getlinedata = (connection, req, res) => {
  connection.query(sql, (err, result) => {
    var data = null;

    if ( err ) {
      console.error(err);
      res.status(200).json({
        status: "fail",
        data: data,
      });
      return;
    } else {
      data = [];

      result.forEach(item => {
        if ( item.id >= 1 && item.id <= 3) {
          var fl = fs.readFileSync(path.join(path.join(__dirname, "data"), "line"+item.id+".json"), "utf8");

          if ( !fl ) {
            console.error("file json"+item.id+".json read error!");
            res.status(200).json({
              status: "fail",
              data: null,
            });
            return;
          } else {
            data.push({
              id: item.id,
              data: JSON.parse(fl).data
            });
          }
        }
      });

      res.status(200).json({
        status: "success",
        data: data,
      });
    }
  });
}

module.exports = getlinedata;